package utils

import (
	"fmt"
	"log"
	"my_git_repos/gocn_daily_news/controllers/crawl/types"
	"regexp"
	"strconv"
	"strings"
	"time"
)

var ReContent = regexp.MustCompile(`了问题 • (\d+) 人关注 • (\d+) 个回复 • (\d+) 次浏览 • (.*)`)

func ContentConstructor(content string) types.Content {
	// 发起了问题 • 1 人关注 • 0 个回复 • 182 次浏览 • 3 小时前
	//splitList := strings.Split(content, "•")
	//if len(splitList) != 5 {
	//	panic("splitList length err")
	//}
	matches := ReContent.FindAllStringSubmatch(content, 1)

	if len(matches) <= 0 {
		return types.Content{}
	}

	subMatch := matches[0]
	// follow
	follow, _ := strconv.Atoi(subMatch[1])

	// reply
	reply, _ := strconv.Atoi(subMatch[2])

	// view
	view, _ := strconv.Atoi(subMatch[3])

	// publishTime
	publishTimeStr := strings.TrimSpace(subMatch[4])
	publishTime := ParsePublishTime(publishTimeStr)
	return types.NewContent(follow, reply, view, publishTime)
}

func ParsePublishTime(publishTime string) time.Time {
	publishTime = strings.TrimSpace(publishTime)
	if strings.Contains(publishTime, "小时前") {
		hours, _ := strconv.Atoi(strings.TrimSpace(strings.TrimRight(publishTime, "小时前")))
		return ParseHoursAge(hours)
	} else if strings.Contains(publishTime, "天前") {
		days, _ := strconv.Atoi(strings.TrimSpace(strings.TrimRight(publishTime, "天前")))
		return ParseHoursAge(24 * days)
	} else {
		t, _ := StrToTime(publishTime)
		return t
	}
}

func ParseHoursAge(hours int) time.Time {
	subTimes, _ := time.ParseDuration(fmt.Sprintf("-%dh", hours))
	return time.Now().Add(subTimes)
}

func StrToTime(str string) (time.Time, error) {
	// 2018-11-09 11:19
	// 格式化
	t := "2006-01-02 15:04"
	// 日期字符串
	loc, _ := time.LoadLocation("Local")
	myTime, err := time.ParseInLocation(t, str, loc)
	if err != nil {
		log.Println("StrToTime Error: ", err)
		return time.Now(), err
	}
	return myTime, nil
}
